package com.metadata_system.system.service;

import com.alibaba.fastjson.JSON;
import com.metadata_system.common.db.entity.Config;
import com.metadata_system.common.db.mapper.ConfigMapper;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.system.request.ConfigListParams;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("systemConfigService")
public class ConfigService {

    @Autowired(required = false)
    ConfigMapper configMapper;

    /**
     * 获取配置列表
     *
     * @return
     */
    public ApiResult getList(ConfigListParams listParams) {
        Example example = new Example(Config.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isBlank(listParams.getName())) {
            criteria.andLike("name", "%" + listParams.getName() + "%");
        }
        listParams.setOrder(example,"id,updatedTime");
        int i = this.configMapper.selectCountByExample(example);
        List<Config> configs = new ArrayList<>();
        if (i > 0) {
            configs = this.configMapper.selectByExampleAndRowBounds(example, listParams.getRowRunds());
        }
        return ApiResult.successPage(configs, i);
    }

    /**
     * 设置值
     *
     * @param myKey   存储key
     * @param name    标记名称
     * @param content 存储内容
     * @param userId 操作管理员ID
     * @return
     */
    public ApiResult setKeyValue(String myKey, String name, String content,Integer userId) {
        if (StringUtils.isEmpty(myKey)) {
            return ApiResult.error("存储Key 不能为空");
        }
        if (name.length() > 50) {
            return ApiResult.error("名称长度 不能超过50");
        }
        if (myKey.length() > 50) {
            return ApiResult.error("key长度 不能超过50");
        }
        if (content.length() > 20000) {
            return ApiResult.error("内容长度 不能超过20000");
        }
        Integer id = this.configMapper.getIdByKey(myKey);
        Config updateConfig = Config.builder()
                .myKey(myKey)
                .name(name)
                .content(content)
                .updatedTime(new Date())
                .build();
        if (id == null) {
            this.configMapper.insertSelective(updateConfig);
        } else {
            updateConfig.setId(id);
            this.configMapper.updateByPrimaryKeySelective(updateConfig);
        }


        return ApiResult.success();
    }

    /**
     * 删除-配置
     *
     * @return
     */
    public ApiResult delete(Integer id,Integer userId) {
        Config currConfig = this.configMapper.selectByPrimaryKey(id);
        if (currConfig==null){
            return ApiResult.error("删除数据不存在");
        }
        this.configMapper.deleteByPrimaryKey(id);
        return ApiResult.success();
    }
}
